import Vue from "vue";
import Router from "vue-router";
import { LoadingBar } from "iview";
import store from "../store/index";
import { routes } from "./router"; //路由的文件名不能命名为route.js，否则路由失效
import { hasPerssion } from "@/utils/tools";

Vue.use(Router);
let base = `${process.env.BASE_URL}`; // 动态获取二级目录

const router = new Router({
  mode: "hash",
  base,
  routes
});

//全局路由钩子函数--->Vue单页应用，使用vue-router设置每个页面的title
router.beforeEach((to, from, next) => {
  //console.log("---------beforeEach-------------");
  LoadingBar.start();
  //地址栏直接访问不需要token的路由，则进登录页面拦截
  const unToken = store.state.unToken;
  if (unToken.includes(to.path)) {
    next();
    return;
  }
  //判断是否有token信息
  const token = store.state.token;
  if (!token || token === "") {
    // 未登录跳转至登录页
    LoadingBar.error();
    next("/login");
    return;
  }
  //判断相应的菜单权限
  turnTo(to, next);
});
export const turnTo = (to, next) => {
  const permissions = to.meta ? to.meta.permissions : [];
  if (hasPerssion(permissions, store.state.permissions)) {
    //有权限
    next();
  } else {
    //无权限，重定向401
    LoadingBar.error();
    next({ replace: true, path: "/401" });
  }
};
router.afterEach(to => {
  //console.log("------------afterEach-------------");
  window.document.title = to.meta ? to.meta.title : "miaomei-admin";
  LoadingBar.finish();
});

export default router;
